<template>
  <section>
    <!-- 工具栏 -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="condition">
        <el-form-item>
          <el-select
            v-model="condition._area"
            placeholder="区域编号"
            @change="areaChange(condition._area, 'search')"
            clearable
          >
            <el-option
              v-for="item in area"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="condition._dorm"
            placeholder="宿舍楼编号"
            @change="dormChange(condition._dorm, 'search')"
            clearable
          >
            <el-option
              v-for="item in dorm"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="condition._floor"
            placeholder="楼层"
            @change="floorChange(condition._floor, 'search')"
            clearable
          >
            <el-option
              v-for="item in floor"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="condition._roomNumber" placeholder="房间号" clearable>
            <el-option
              v-for="item in roomNumber"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!-- 操作栏 -->
    <el-col>
      <el-form :inline="true">
        <el-form-item>
          <el-button size="small" type="success" @click="newFormVisible = true">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="success" @click="outExcel">导出EXCEL</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!-- 数据展示 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="selsChange"
      v-loading="Loading"
    >
      <el-table-column align="center" type="selection" fixed width="50"></el-table-column>
      <el-table-column align="center" label="序号" fixed type="index" width="50"></el-table-column>
      <el-table-column align="center" label="区域名称" prop="affiliationName" fixed min-width="100"></el-table-column>
      <el-table-column align="center" label="宿舍楼名称" prop="dormName" min-width="80"></el-table-column>
      <el-table-column align="center" label="房间名称" prop="roomNumber" min-width="80"></el-table-column>
      <el-table-column align="center" label="资产名称" prop="goodsName" min-width="100"></el-table-column>
      <el-table-column align="center" label="资产编号" prop="goodsNumber" min-width="100"></el-table-column>
      <el-table-column align="center" label="单价" prop="unitPrice" min-width="60"></el-table-column>
      <el-table-column align="center" label="赔偿价格" prop="compensationPrice" min-width="60"></el-table-column>
      <el-table-column align="center" label="资产数量" prop="count" min-width="50"></el-table-column>
      <el-table-column align="center" label="备注" prop="remark" min-width="150"></el-table-column>
      <el-table-column align="center" label="操作" min-width="150">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-col :span="24" class="toolbar">
      <el-pagination
        @current-change="currentChange"
        :current-page="currentPage"
        :total="totalPage"
        style="float:right;"
      ></el-pagination>
    </el-col>

    <!-- 新建 -->
    <el-dialog
      title="新增"
      :visible.sync="newFormVisible"
      :close-on-click-modal="false"
      class="newDialog"
    >
      <el-form label-width="6rem" ref="newForm" :model="newGoods" :rules="rule">
        <el-form-item label="所属区域" prop="_area">
          <el-select
            v-model="newGoods._area"
            placeholder="区域编号"
            @change="areaChange(newGoods._area, 'new')"
          >
            <el-option
              v-for="item in area"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属宿舍楼" prop="_dorm">
          <el-select
            v-model="newGoods._dorm"
            placeholder="宿舍楼编号"
            @change="dormChange(newGoods._dorm, 'new')"
          >
            <el-option
              v-for="item in dorm"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属楼层" prop="_floor">
          <el-select
            v-model="newGoods._floor"
            placeholder="楼层编号"
            @change="floorChange(newGoods._floor, 'new')"
          >
            <el-option
              v-for="item in floor"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间号" prop="_roomNumber">
          <el-select v-model="newGoods._roomNumber" placeholder="房间编号">
            <el-option
              v-for="item in roomNumber"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 重复行 -->
        <el-row>
          <el-col :span="4">
            <el-form-item
              v-for="(goods, index) in newGoods.goods"
              label="物品名称"
              :key="goods.key"
              :prop="'goods.' + index + '.goodsName'"
              :rules="{required: true, message: '不能为空', trigger: 'blur'}"
            >
              <el-input v-model="goods.goodsName" style="width:8rem" placeholder="用品名称"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item
              v-for="(goods, index) in newGoods.goods"
              label="物品编码"
              :key="goods.key"
              :prop="'goods.' + index + '.goodsNumber'"
              :rules="{required: true, message: '不能为空', trigger: 'blur'}"
            >
              <el-input
                v-model="goods.goodsNumber"
                style="width:8rem"
                placeholder="用品编码"
                @blur="checkGoodsName(goods.goodsNumber,index)"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item
              v-for="(goods, index) in newGoods.goods"
              label="单价"
              :key="goods.key"
              :prop="'goods.' + index + '.unitPrice'"
              :rules="[{required: true, message: '不能为空', trigger: 'blur'},{ type: 'number', message: '值必须为数字值'}]"
            >
              <el-input v-model.number="goods.unitPrice" placeholder="单价" style="width:8rem"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item
              v-for="(goods, index) in newGoods.goods"
              label="赔偿价格"
              :key="goods.key"
              :prop="'goods.' + index + '.compensationPrice'"
              :rules="[{required: true, message: '不能为空', trigger: 'blur'},{ type: 'number', message: '值必须为数字值'}]"
            >
              <el-input
                v-model.number="goods.compensationPrice"
                placeholder="赔偿价格"
                style="width:8rem"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item
              v-for="(goods, index) in newGoods.goods"
              label="数量"
              :key="goods.key"
              :prop="'goods.' + index + '.count'"
              :rules="[{required: true, message: '不能为空', trigger: 'blur'},{ type: 'number', message: '值必须为数字值'}]"
            >
              <el-input v-model="goods.count" disabled placeholder="数量" style="width:5rem"></el-input>&nbsp;&nbsp;&nbsp;&nbsp;
              <el-button @click.prevent="removeGoods(goods)" size="small" type="danger">删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button @click="addGoods" type="success">新增资产</el-button>
        <el-button @click="resetNewForm('newForm')">重置</el-button>
        <el-button type="primary" @click="newSubmit('newForm')" :loading="newLoading">提交</el-button>
      </div>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog title="编辑" :visible.sync="alterFormVisible" :close-on-click-modal="false">
      <el-form label-width="6rem" ref="alterForm" :model="alterGoods" :rules="rule">
        <el-form-item label="所属区域">
          <el-input v-model="alterGoods.affiliationName" disabled placeholder="用品名称"></el-input>
        </el-form-item>
        <el-form-item label="所属区域">
          <el-input v-model="alterGoods.dormName" disabled placeholder="用品名称"></el-input>
        </el-form-item>
        <el-form-item label="房间号">
          <el-input v-model="alterGoods.roomNumber" disabled placeholder="用品名称"></el-input>
        </el-form-item>
        <el-form-item label="用品名称" prop="goodsName">
          <el-input v-model="alterGoods.goodsName" placeholder="用品名称"></el-input>
        </el-form-item>
        <el-form-item label="资产编码">
          <el-input v-model="alterGoods.goodsNumber" disabled placeholder="资产编码"></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="alterGoods.unitPrice" placeholder="单价"></el-input>
        </el-form-item>
        <el-form-item label="赔偿价格" prop="compensationPrice">
          <el-input v-model="alterGoods.compensationPrice" placeholder="赔偿价格"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="alterGoods.count" disabled placeholder="数量"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="alterGoods.remark" placeholder="备注" type="textarea" autosize></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="alterFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click.native="alterSubmit('alterForm')"
          :loading="alterLoading"
        >提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { getArea } from "../../api/area.js";
import { getDorm, getFloor } from "../../api/dorm.js";
import { getRoom } from "../../api/room.js";
import {
  getRoomGoods,
  newRoomGoods,
  checkNumberRepeat,
  altertRoomGoods,
  deleteRoomGoods
} from "../../api/goods.js";
export default {
  data() {
    // 进行数字验证
    var checkNumber = (rule, value, callback) => {
      var re = /^[0-9]+.?[0-9]*$/;
      if (!value) {
        return callback(new Error("值不能为空"));
      }
      setTimeout(() => {
        if (!re.test(value)) {
          callback(new Error("请输入数字值"));
        } else {
          callback();
        }
      }, 100);
    };
    return {
      condition: {
        _area: null,
        _dorm: null,
        _floor: null,
        roomNumber: null,
        page: 1
      },
      tableData: [
        {
          affiliationName: null,
          affiliationNumber: null,
          dormName: null,
          dormNumber: null,
          roomNumber: null,
          goodsName: null,
          goodsNumber: null,
          unitPrice: null,
          compensationPrice: null,
          count: null,
          _type: null,
          _date: null,
          floor: null,
          remark: null
        }
      ],
      newGoods: {
        _area: null,
        _dorm: null,
        _floor: null,
        _roomNumber: null,
        goods: [
          {
            goodsName: null,
            goodsNumber: null,
            unitPrice: null,
            compensationPrice: null,
            count: 1,
            remark: null
          }
        ]
      },
      alterGoods: {
        _affiliationName: null,
        _dorm: null,
        _roomNumber: null,
        goodsName: null,
        goodsNumber: null,
        unitPrice: null,
        compensationPrice: null,
        count: null,
        remark: null
      },
      area: [
        {
          value: "",
          label: ""
        }
      ],
      dorm: [
        {
          value: "",
          label: ""
        }
      ],
      floor: [
        {
          value: "1",
          label: "1"
        },
        {
          value: "2",
          label: "2"
        },
        {
          value: "3",
          label: "3"
        },
        {
          value: "4",
          label: "4"
        },
        {
          value: "5",
          label: "5"
        },
        {
          value: "6",
          label: "6"
        }
      ],
      roomNumber: [
        {
          value: "",
          label: ""
        }
      ],
      rule: {
        _area: [{ required: true, message: "请选择区域", trigger: "change" }],
        _dorm: [{ required: true, message: "请选择宿舍楼", trigger: "change" }],
        _floor: [{ required: true, message: "请选择楼层", trigger: "change" }],
        _roomNumber: [
          { required: true, message: "请选择房间", trigger: "change" }
        ],
        goodsName: [{ required: true, message: "不能为空", trigger: "blur" }],
        unitPrice: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
            validator: checkNumber
          }
        ],
        compensationPrice: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
            validator: checkNumber
          }
        ],
        remark: [{ trigger: "blur" }]
      },
      Loading: false,
      newFormVisible: false,
      newLoading: false,
      alterFormVisible: false,
      alterLoading: false,
      currentPage: 1,
      totalPage: 1
    };
  },
  methods: {
    getArea() {
      getArea().then(res => {
        if (res) {
          this.area = res.msg;
        }
      });
    },
    // 选完区域后触发宿舍楼
    areaChange(area, type) {
      if (area === "") {
        return true;
      }
      // 根据类别来清空数据
      if (type === "new") {
        this.newGoods._dorm = "";
        this.newGoods._floor = "";
        this.newGoods._roomNumber = "";
      } else if (type === "search") {
        this.condition._dorm = "";
        this.condition._floor = "";
        this.condition.roomNumber = "";
      }
      // 搜索宿舍楼编号
      getDorm(area).then(res => {
        if (res) {
          // this.condition._dorm = null;
          this.dorm = res.msg;
        } else {
          this.dorm = [
            {
              value: "",
              label: ""
            }
          ];
          // this.condition._dorm = "";
        }
      });
    },
    // 选完宿舍楼后触发楼层
    dormChange(dorm, type) {
      if (dorm === "") {
        return true;
      }
      if (type === "new") {
        this.newGoods._floor = "";
        this.newGoods._roomNumber = "";
      } else if (type === "search") {
        this.condition._floor = "";
        this.condition.roomNumber = "";
      }
      let _area =
        type === "search"
          ? this.condition._area
          : type === "new"
          ? this.newGoods._area
          : null;
      // 获取当前楼层
      getFloor(_area, dorm).then(res => {
        if (res) {
          this.floor = [];
          let floor = res.msg[0].d_layers;
          for (let i = 1; i <= floor; i++) {
            let _floor = { value: i, label: i };
            this.floor.push(_floor);
          }
        }
      });
    },
    // 选完楼层后触发房间
    floorChange(floor, type) {
      if (type === "new") {
        this.newGoods._roomNumber = "";
      } else if (type === "search") {
        this.condition.roomNumber = "";
      }
      let _area =
        type === "search"
          ? this.condition._area
          : type === "new"
          ? this.newGoods._area
          : null;
      let _dorm =
        type === "search"
          ? this.condition._dorm
          : type === "new"
          ? this.newGoods._dorm
          : null;
      // 获取房间
      console.log(_area, _dorm, floor);
      getRoom(_area, _dorm, floor, "3").then(res => {
        if (res) {
          this.roomNumber = [];
          this.roomNumber = res.msg;
        }
      });
    },
    getData() {
      this.Loading = true;
      getRoomGoods(this.condition).then(res => {
        this.Loading = false;
        if (res) {
          this.totalPage = res.page;
          this.tableData = res.msg;
        } else {
          this.tableData = null;
          this.totalPage = 0;
          this.currentPage = 0;
        }
      });
    },
    // 查询
    search() {
      this.condition.page = 1;
      this.getData();
    },
    // 分页
    currentChange(val) {
      this.condition.page = val === undefined ? this.currentPage : val;
      this.getData();
    },
    // 新建
    newSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.newLoading = true;
          newRoomGoods(this.newGoods).then(res => {
            this.$message.success(res.msg);
            this.$refs[formName].resetFields();
            this.newLoading = false;
            this.getData();
          });
        }
      });
    },
    // TODO: 导出
    outExcel() {
      window.location.href =
        "http://192.168.10.225:80/dormitoryA/Property/Property/roomGoodsExcelOut";
    },
    // 点击编辑
    handleEdit(index, row) {
      this.alterFormVisible = true;
      this.alterGoods = Object.assign({}, row);
    },
    //修改
    alterSubmit(forName) {
      this.$refs[forName].validate(valid => {
        if (valid) {
          this.alterLoading = true;
          altertRoomGoods(this.alterGoods).then(res => {
            this.alterLoading = false;
            if (res) {
              this.$message.success(res.msg);
            }
            this.getData();
            this.alterFormVisible = false;
            return true;
          });
        } else {
          this.$message.error("请将信息填写完整!");
          return false;
        }
      });
    },
    // 点击删除
    handleDel(row) {
      this.$confirm("此操作将永久删除该物品, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteRoomGoods(row.serial).then(res => {
            if (res) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getData();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    selsChange: function(sels) {
      this.sels = sels;
    },
    addGoods() {
      this.newGoods.goods.push({
        goodsName: null,
        goodsNumber: null,
        unitPrice: null,
        compensationPrice: null,
        count: 1,
        key: Date.now()
      });
    },
    removeGoods(item) {
      var index = this.newGoods.goods.indexOf(item);
      if (index !== -1) {
        this.newGoods.goods.splice(index, 1);
      }
    },
    resetNewForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 防止物品编号重复
    checkGoodsName(goodsNumber, index) {
      // 先检验是否与重复行中的相同
      this.Loading = true;
      for (let i = 0; i < this.newGoods.goods.length; i++) {
        if (this.newGoods.goods[i].goodsNumber === goodsNumber) {
          if (i !== index) {
            this.Loading = false;
            this.$message.error("编码重复!");
            this.newGoods.goods[index].goodsNumber = "";
            return false;
          }
        }
      }
      // 与已存在的编码进行验证
      checkNumberRepeat(goodsNumber, "room").then(res => {
        if (!res) {
          this.Loadingg = false;
          this.$message.error("编码重复!");
          this.newGoods.goods[index].goodsNumber = "";
          return false;
        } else {
          this.Loading = false;
          return true;
        }
      });
    }
  },
  mounted() {
    this.getArea();
    this.getData();
  }
};
</script>
<style lang="">
.newDialog {
  width: 150%;
  margin: auto;
  left: -25rem;
}
</style>